// src/global.rs

use std::fs::OpenOptions;

use clap::Parser;
use lazy_static::lazy_static;
use log::{error, LevelFilter};
use simplelog::{
    format_description, ColorChoice, CombinedLogger, ConfigBuilder, TermLogger, TerminalMode,
    WriteLogger,
};
use time::UtcOffset;

use crate::args::CmdLineArgs;
use crate::config::IndexerConfig;

// 全局变量的类型定义
pub struct GlobalData {
    pub config: IndexerConfig,
    pub args: CmdLineArgs,
}

// 初始化全局变量的函数
fn init_global_data() -> GlobalData {
    let args: CmdLineArgs = CmdLineArgs::parse();
    init_logger(&args);
    match IndexerConfig::parse(args.config()) {
        Ok(config) => GlobalData { args, config },
        Err(e) => {
            error!("failed to read {:?}: {}", args.config(), e);
            std::process::exit(1);
        }
    }
}

// 定义一个包含全局变量的 Mutex
lazy_static! {
    static ref GLOBAL_DATA: GlobalData = init_global_data();
}

// 对外提供的操作全局变量的方法
pub fn get_global_config() -> IndexerConfig {
    GLOBAL_DATA.config.clone()
}

pub fn get_global_args() -> CmdLineArgs {
    GLOBAL_DATA.args.clone()
}

/// init logger with file and terminal logs
///
/// # Arguments
///
/// * `CmdLineArgs` - command line arguments
///
fn init_logger(args: &CmdLineArgs) {
    let time_offset = UtcOffset::current_local_offset().expect("");
    let config = ConfigBuilder::new()
        .set_time_format_custom(format_description!(
            "[year]-[month]-[day] [hour]:[minute]:[second]"
        ))
        .set_time_offset(time_offset)
        .build();
    let config_file = config.clone();

    CombinedLogger::init(vec![
        TermLogger::new(LevelFilter::Info, config, TerminalMode::Mixed, ColorChoice::Auto),
        WriteLogger::new(
            LevelFilter::Info,
            config_file,
            OpenOptions::new().append(true).create(true).open(args.log()).unwrap(),
        ),
    ])
    .unwrap();
}
